package net.cmbt.okframe.okwebview.view;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.helper.loadviewhelper.help.OnLoadViewListener;
import com.helper.loadviewhelper.load.LoadViewHelper;

import net.cmbt.okframe.R;
import net.cmbt.okframe.okwebview.LookPicActivity;
import net.cmbt.okframe.okwebview.SuperWebView;
import net.cmbt.okframe.okwebview.SuperWebView1;
import net.cmbt.okframe.okwebview.inteface.SwebLoadListener;

import static android.content.Context.DOWNLOAD_SERVICE;

public class SuperWebLayout extends LinearLayout {

    private View view;
    public WebView superWebview;
    public SuperWebView builder;
    Activity activity;
    private float mPx;
    private float mPy;
    SwebLoadListener swebLoadListener;
    private TextView helper_load_tv;
    private LoadViewHelper helper_load;
    private boolean isFinish;
    private boolean isError;

    public SuperWebLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        layout(context);
    }

    public SuperWebLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        layout(context);
    }

    private void layout(Context context) {
        view = LayoutInflater.from(context).inflate(R.layout.activity_okweb, this);
        superWebview = (WebView) view.findViewById(R.id.superweb_webview);
        helper_load_tv = (TextView) view.findViewById(R.id.helper_load_tv);
        helper_load = new LoadViewHelper(helper_load_tv);
        helper_load.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                helper_load.showLoading("加载中...");
                superWebview.reload();
            }
        });
    }


    public void with(SuperWebView builder, Activity mainActivity) {
        this.builder = builder;
        this.activity = mainActivity;
        swebLoadListener = (SwebLoadListener) mainActivity;
        load();
    }

    public void with(SuperWebView builder, Fragment mainActivity) {
        this.builder = builder;
        this.activity = mainActivity.getActivity();
        swebLoadListener = (SwebLoadListener) mainActivity;
        load();
    }

    private void load() {
        WebSettings webSettings = superWebview.getSettings();
        webSettings.setJavaScriptEnabled(builder.isSupportJS()); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(builder.isSupportAccessFiles()); // 允许访问文件
        webSettings.setBuiltInZoomControls(builder.isBuiltInZoomControls()); // 设置显示缩放按钮
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //缓存模式
        webSettings.setAppCacheEnabled(true); //app缓存
        String head = "<head><style>* {font-size:40px}{color:#212121;}img{max-width: 100%; width:100%; height: auto;  }</style></head>";
        if (builder.getUrl() != null) {
            superWebview.loadUrl(builder.getUrl());
        } else if (builder.getHtmlData() != null) {
            String resultStr = "<html>" + head + "<body>" + builder.getHtmlData() + "</body></html>";
            superWebview.loadDataWithBaseURL(null, resultStr, "text/html", "utf-8", null);
        } else {
            String resultStr = "<html>" + head + "<body>" + "您未设置URL，请在SuperWebView对象下setUrl()或者setHtmlData()" + "</body></html>";
            superWebview.loadDataWithBaseURL(null, resultStr, "text/html", "utf-8", null);
        }

        webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
        webSettings.setUseWideViewPort(true);// 关键点
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setDisplayZoomControls(false);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webSettings.setLoadWithOverviewMode(true);
        // 解决有些比较大的H5页面显示超出屏幕的问题 end
        // 开启 DOM storage API 功能
        superWebview.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        superWebview.getSettings().setDatabaseEnabled(true);
        superWebview.addJavascriptInterface(SuperWebView1.jsCallback, SuperWebView1.SwebManager.Web.jsInterfaceName);
        int mDensity = getResources().getDisplayMetrics().densityDpi;
        if (mDensity == 240) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 120) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == DisplayMetrics.DENSITY_TV) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        }
        WebChromeClientImpl chromeClient = new WebChromeClientImpl();
        superWebview.setWebChromeClient(chromeClient);

        superWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                isError = false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }


            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                isError = true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (SuperWebView1.SwebManager.Web.supportCallSMS) {
                    if (url.startsWith("tel:")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        activity.startActivity(intent);
                        return true;
                    }

                    if (url.startsWith("sms:")) {
                        try {
                            String replace = url.replace("sms:", "");
                            replace = replace.replace("body=", "");
                            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + replace.substring(0, replace.indexOf("?"))));
                            intent.putExtra("sms_body", replace.substring(replace.indexOf("?") + 1, replace.length()));
                            activity.startActivity(intent);
                        } catch (Exception e) {
                        }
                        return true;
                    }

                    view.loadUrl(url);
                } else {
                    return false;
                }


                return false;
            }
        });


        //返回按键的处理
        superWebview.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (swebLoadListener != null)
                    swebLoadListener.goBackListener(v, keyCode, event);

                if (builder.isUseGoBack()) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            if (superWebview.canGoBack()) {
                                superWebview.goBack();
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
        });


        superWebview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String s1, String s2, String s3, long l) {
                Log.e("", "获取到的下载地址：：：" + url);
                if (swebLoadListener != null)
                    swebLoadListener.onDownloadStart(url, s1, s2, s3, l);

                switch (SuperWebView1.SwebManager.Web.downFileType) {

                    case 1:
                        //跳转浏览器下载
                        Uri uri = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        activity.startActivity(intent);
                        break;

                    case 2:
                        //系统下载
                        // 指定下载地址
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
                        request.allowScanningByMediaScanner();
                        // 设置通知的显示类型，下载进行时和完成后显示通知
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        // 设置通知栏的标题，如果不设置，默认使用文件名
                        // request.setTitle("This is title");
                        // 设置通知栏的描述
                        //request.setDescription("This is description");
                        // 允许在计费流量下下载
                        request.setAllowedOverMetered(false);
                        // 允许该记录在下载管理界面可见
                        request.setVisibleInDownloadsUi(false);
                        // 允许漫游时下载
                        request.setAllowedOverRoaming(true);
                        // 允许下载的网路类型
                        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
                        // 设置下载文件保存的路径和文件名
                        String fileName = URLUtil.guessFileName(url, SuperWebView1.SwebManager.Web.downFilePath, url);
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
                        // 外可选一下方法，自定义下载路径bj8
                        // request.setDestinationUri()
                        // request.setDestinationInExternalFilesDir()
                        final DownloadManager downloadManager = (DownloadManager) activity.getSystemService(DOWNLOAD_SERVICE);
                        // 添加一个下载任务
                        long downloadId = downloadManager.enqueue(request);
                        break;
                }

            }
        });


        superWebview.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mPx = motionEvent.getRawX();
                mPy = motionEvent.getRawY();
                return false;
            }
        });


        superWebview.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                try {

//                    WebView.HitTestResult result = sWebView.getHitTestResult();
                    WebView.HitTestResult result = ((WebView) view).getHitTestResult();
                    if (null == result)
                        return false;
                    int type = result.getType();
                    switch (type) {
                        case WebView.HitTestResult.EDIT_TEXT_TYPE: // 选中的文字类型
                            break;
                        case WebView.HitTestResult.PHONE_TYPE: // 处理拨号
                            break;
                        case WebView.HitTestResult.EMAIL_TYPE: // 处理Email
                            break;
                        case WebView.HitTestResult.GEO_TYPE: // 　地图类型
                            break;
                        case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
                            break;
                        case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: // 带有链接的图片类型

                            break;
                        case WebView.HitTestResult.IMAGE_TYPE: // 处理长按图片的菜单项

                            try {
                                final String url = result.getExtra();
                                // TODO Auto-generated method stub
                                // 将布局文件转换成View对象，popupview 内容视图
                                View mPopView = activity.getLayoutInflater().inflate(R.layout.popwindow_layout, null);
                                // 将转换的View放置到 新建一个popuwindow对象中
                                final PopupWindow mPopupWindow = new PopupWindow(mPopView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                                // 点击popuwindow外让其消失
                                mPopupWindow.setOutsideTouchable(true);
                                // mpopupWindow.setBackgroundDrawable(background);

                                if (mPopupWindow.isShowing()) {
                                    mPopupWindow.dismiss();
                                } else {
                                    // 设置PopupWindow 显示的形式 底部或者下拉等
                                    // 在某个位置显示
//                            mPopupWindow.showAtLocation(mPopView, Gravity.BOTTOM, (int)mPx, (int)mPy);
                                    mPopupWindow.showAtLocation(mPopView, Gravity.TOP | Gravity.START, (int) mPx + 50, (int) mPy);
                                }
                                TextView look_pic = (TextView) mPopView.findViewById(R.id.look_pic);
                                look_pic.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Intent intent = new Intent(activity, LookPicActivity.class);
                                        intent.putExtra("path", url);
                                        activity.startActivity(intent);
                                        mPopupWindow.dismiss();
                                    }
                                });
                            } catch (Exception e) {

                            }
                            return true;
                        case WebView.HitTestResult.UNKNOWN_TYPE: //未知
                            break;
                    }

                } catch (Exception e) {
                    Log.e("捕捉的异常信息是:", "" + e.getMessage());
                }
                return false;
            }

        });
    }


    class WebChromeClientImpl extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            swebLoadListener.onProgressChanged(view, newProgress);
            super.onProgressChanged(view, newProgress);

            Log.e("onProg错误中错误中错误中错误中", "");

            if (newProgress < 40) {
                if (!isFinish) {
                    helper_load.showLoading("加载中...");
                }
                isFinish = false;
            }

            if (newProgress > 40) {
                if (isFinish) {
                    if (!isError) {
                        superWebview.setVisibility(View.VISIBLE);
                        helper_load.showContent();
                    } else {
                        superWebview.setVisibility(View.GONE);
                        helper_load.showError();
                    }
                }
                isFinish = true;
                if (!isError) {
                    superWebview.setVisibility(View.VISIBLE);
                    helper_load.showContent();
                } else {
                    superWebview.setVisibility(View.GONE);
                    helper_load.showError();
                }
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            swebLoadListener.onJsAlert(view, url, message, result);
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]>
                filePath, FileChooserParams fileChooserParams) {

            swebLoadListener.onShowFileChooser(webView, filePath, fileChooserParams);
            switch (SuperWebView1.SwebManager.Web.upFileType) {
                case 1:
//                    choseWebFile(filePath);
                    break;

                case 2:
//                    asAppleSeleFile(filePath);
                    break;
            }
            return true;
        }
    }


}
